package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Constants;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    public static final String url = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User wechatLogin(UserLoginDTO userLoginDTO) {

        String openid = getopneid(userLoginDTO.getCode());

        //判断openid是否为空 为空则报异常
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //根据openid查询是否存在该用户
        User user = userMapper.getByopenid(openid);

        //判断user对象是否为空
        if (user == null){
            //不存在该用户  自动创建用户
            user = User.builder().openid(openid).
                           createTime(LocalDateTime.now()).
                           build();

            //创建新用户
            userMapper.insert(user);
        }


        return user;
    }

    private String getopneid(String code){

        //调用微信接口服务获取到用户openid

        Map<String,String> claims = new HashMap<String,String>();
        claims.put("appid",weChatProperties.getAppid());
        claims.put("secret",weChatProperties.getSecret());
        claims.put("js_code",code);
        claims.put("grant_type","authorization_code");

        //发送到微信服务器
        String json = HttpClientUtil.doGet(url, claims);


        /**
         * 从json对象中解析获得openid
         */
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        return openid;
    }
}
